package com.regan.erp.aop;

import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.regan.erp.exception.MyBaselogicException;
import com.regan.erp.model.User;
import com.regan.erp.util.AuthUtil;
import com.regan.erp.util.UserUtil;

import java.lang.reflect.Method;
import java.util.List;

/**
 * 权限拦截器
 *
 * @author zhangby
 * @date 2018/10/24 11:44 AM
 */
public class AuthPermissionInterceptor implements Interceptor {

    /** 验证权限拦截 */
    @Override
    public void intercept(Invocation inv) {
        Controller controller = inv.getController();
        Method method = inv.getMethod();
        User user = UserUtil.getUser(controller.getSession());
        /** 参数非空拦截 */
        AuthPermission authPermission = method.getAnnotation(AuthPermission.class);
        if (ObjectUtil.isNotNull(authPermission)) {
            String[] permission = authPermission.value();
            if (StrKit.notBlank(permission) && !verifyAuth(user.getId(),permission)) {
                throw new MyBaselogicException("800");
            }
        }
        inv.invoke();
    }

    private boolean verifyAuth(String uId,String[] permission) {
        for (String p : permission) {
            //如果授权通过
            if (AuthUtil.verifyAuth(uId, p)) {
                return true;
            }
        }
        return false;
    }
}
